package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.Util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author: zyx
 * @created: 2025-10-11-11:36
 * @description:
 */
@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //强转为HttpServletRequest和HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //获取请求的url
        String url = request.getRequestURI();
        log.info("请求的url是：{}", url);
        //判断请求的url是否是登录
        if(ObjectUtil.equals(url, "/login")){
            chain.doFilter(request, response);
            return;
        }
        //获取请求头中的 token
        String token = request.getHeader("token");
        if(ObjectUtil.isEmpty(token)){
            response.setStatus(401);
            log.info("token为空");
            return;
        }
        //解析token
        try {
            Claims claims = JwtUtil.parseToken(token);
            //获取用户信息
            Object username = claims.get("username");
            log.info("用户是：{}", username);
            Object id = claims.get("id");
            log.info("用户id是：{}", id);
            chain.doFilter(request, response);
            return;
        } catch (Exception e) {
            response.setStatus(401);
            log.info("token验证失败",e);
            return;
        }
    }
}
